package cn.shiro.shiroservice.auth.provider.core;


import cn.shiro.shiroservice.auth.provider.filter.SimpleLoginFilter;
import cn.shiro.shiroservice.auth.utils.JwtUtils;
import cn.shiro.shiroservice.common.constant.HttpRequestManaPoint;
import cn.shiro.shiroservice.common.constant.ManaPoint;
import cn.shiro.shiroservice.common.utils.R;
import io.jsonwebtoken.Claims;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;


/**
 * @author apple
 * <p>
 * &#064;createDate 2023/8/24 13:51
 * @version 1.0.0
 */
public class ShiroDefaultWebSessionManager extends DefaultWebSessionManager {


    private static final Logger log = LoggerFactory.getLogger(ShiroDefaultWebSessionManager.class);


    @Resource
    private SimpleLoginFilter simpleLoginFilter;

    public ShiroDefaultWebSessionManager() {
        super();
    }

    /**
     * 重写父类获取sessionID的方法,若请求为APP或者H5则从请求头中取出token
     *
     * @param request  请求参数
     * @param response 响应参数
     * @return id
     */

    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
        //返回true表示 是登陆 不需要检查token
        boolean isPass = simpleLoginFilter.assertPath((HttpServletRequest) request);
        try {
            if (!isPass) {
                HttpServletRequest httpRequest = WebUtils.toHttp(request);
                String token = httpRequest.getHeader(HttpRequestManaPoint.HTTP_TOKEN);
                if (StringUtils.hasText(token)) {
                    return analysisToken(token);
                }
            }
            return super.getSessionId(request, response);
        } catch (AuthenticationException authenticationException) {
            //这里的id如果返回null的时候 就认为是403
            log.warn("sessionId为null的可能的根本原因:{}", authenticationException.getMessage());
            throw authenticationException;
        }
    }

    /**
     * 解析token
     *
     * @param token 代币
     * @return {@link String}
     */

    protected String analysisToken(String token) {
        Claims claim = JwtUtils.getClaim(token);
        return (String) claim.get(ManaPoint.TOKEN_SESSION_ID);
    }


}

